#include "mqtt_file_transfer.h"
#include <stdlib.h>
#include <string.h>

// 创建文件传输上下文
file_transfer_ctx_t *file_transfer_create(const char *broker, int port, const char *client_id) {
    file_transfer_ctx_t *ctx = malloc(sizeof(file_transfer_ctx_t));
    if (!ctx) {
        return NULL;
    }

    // 初始化MQTT客户端
    ctx->mqtt_client = neu_mqtt_client_new(NEU_MQTT_VERSION_V311);
    if (!ctx->mqtt_client) {
        free(ctx);
        return NULL;
    }

    // 设置MQTT客户端参数
    if (neu_mqtt_client_set_addr(ctx->mqtt_client, broker, port) != 0) {
        neu_mqtt_client_free(ctx->mqtt_client);
        free(ctx);
        return NULL;
    }

    if (neu_mqtt_client_set_id(ctx->mqtt_client, client_id) != 0) {
        neu_mqtt_client_free(ctx->mqtt_client);
        free(ctx);
        return NULL;
    }

    // 设置默认值
    ctx->broker = strdup(broker);
    ctx->port = port;
    ctx->client_id = strdup(client_id);
    ctx->chunk_size = DEFAULT_CHUNK_SIZE;
    ctx->progress_cb = NULL;
    ctx->complete_cb = NULL;
    ctx->user_data = NULL;

    // 打开MQTT客户端
    if (neu_mqtt_client_open(ctx->mqtt_client) != 0) {
        free(ctx->broker);
        free(ctx->client_id);
        neu_mqtt_client_free(ctx->mqtt_client);
        free(ctx);
        return NULL;
    }

    return ctx;
}

// 销毁文件传输上下文
void file_transfer_destroy(file_transfer_ctx_t *ctx) {
    if (ctx) {
        if (ctx->mqtt_client) {
            neu_mqtt_client_close(ctx->mqtt_client);
            neu_mqtt_client_free(ctx->mqtt_client);
        }
        free(ctx->broker);
        free(ctx->client_id);
        free(ctx);
    }
}

// 设置回调函数
void file_transfer_set_callbacks(file_transfer_ctx_t *ctx,
                                 transfer_progress_cb progress_cb,
                                 transfer_complete_cb complete_cb,
                                 void *user_data) {
    if (ctx) {
        ctx->progress_cb = progress_cb;
        ctx->complete_cb = complete_cb;
        ctx->user_data = user_data;
    }
}
